<template>
  <view class="viewport">
    <!-- 固定顶部导航栏 -->
    <view class="fixed-top">
      <fui-nav-bar
        background="#0052D9"
        title="筛选"
        color="#fff"
        isFixed
        @leftClick="leftClick"
      >
        <fui-icon color="#fff" name="arrowleft"></fui-icon>
      </fui-nav-bar>
    </view>

    <!-- 主内容区域，可滚动 -->
    <view class="main-content">
      <view class="warp">
        <view class="ul">
          <view class="li">
            <fui-input
              v-model="formData.subject"
              label="工单主题"
              borderTop
              placeholder="请输入"
            ></fui-input>
            <fui-input
              v-model="formData.orderNo"
              label="工单单号"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>
            <fui-input
              v-model="formData.repairNo"
              label="报修单号"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>
            <fui-input
              v-model="formData.dispatchPerson"
              label="派工人员"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>
            <view class="time-range">
              <fui-input
                v-model="formData.repairTimeRange"
                label="维修时间"
                :bottomLeft="0"
                placeholder="请选择时间区间"
                @click="showRepairTime = true"
              >
                <fui-icon :size="50" name="arrowright"></fui-icon>
              </fui-input>
            </view>
            <fui-input
              v-model="formData.repairTeam"
              label="维修班组"
              :bottomLeft="0"
              placeholder="请选择"
            >
              <fui-icon
                :size="50"
                name="arrowright"
                @click="handleShowTeam"
              ></fui-icon>
            </fui-input>
            <fui-input
              v-model="formData.repairPerson"
              label="维修负责人"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>
            <fui-input
              v-model="formData.faultReason"
              label="故障原因"
              :bottomLeft="0"
              placeholder="请选择"
            >
              <fui-icon
                :size="50"
                name="arrowright"
                @click="handleShowFault"
              ></fui-icon>
            </fui-input>
            <fui-input
              v-model="formData.repairLevel"
              label="维修级别"
              :bottomLeft="0"
              placeholder="请选择"
            >
              <fui-icon
                :size="50"
                name="arrowright"
                @click="showLevel = true"
              ></fui-icon>
            </fui-input>
            <fui-input
              v-model="formData.repairType"
              label="维修类型"
              :bottomLeft="0"
              placeholder="请选择"
            >
              <fui-icon
                :size="50"
                name="arrowright"
                @click="showType = true"
              ></fui-icon>
            </fui-input>
            <fui-input
              v-model="formData.emergency"
              label="紧急程度"
              :bottomLeft="0"
              placeholder="请选择"
            >
              <fui-icon
                :size="50"
                name="arrowright"
                @click="show = true"
              ></fui-icon>
            </fui-input>
            <fui-input
              v-model="formData.deviceName"
              label="设备名称"
              :bottomLeft="0"
              placeholder="请选择"
            >
              <fui-icon
                :size="50"
                name="arrowright"
                @click="handleDeviceSelect"
              ></fui-icon>
            </fui-input>
            <fui-input
              v-model="formData.useDepartment"
              label="使用部门"
              :bottomLeft="0"
              placeholder="请选择"
            >
              <fui-icon
                :size="50"
                name="arrowright"
                @click="handleShowDepartment"
              ></fui-icon>
            </fui-input>
            <fui-input
              v-model="formData.receiver"
              label="验收人"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>
            <view class="time-range">
              <fui-input
                v-model="formData.receiveStartTime"
                label="验收时间"
                :bottomLeft="0"
                placeholder="请选择时间区间"
                @click="showReceiveTime = true"
              >
                <fui-icon :size="50" name="arrowright"></fui-icon>
              </fui-input>
            </view>
            <fui-input
              v-model="formData.status"
              label="状态"
              :bottomLeft="0"
              placeholder="请选择"
            >
              <fui-icon
                :size="50"
                name="arrowright"
                @click="showStatus = true"
              ></fui-icon>
            </fui-input>
          </view>
        </view>

        <!-- 各种选择器 -->
        <fui-picker
          :options="options"
          :show="show"
          @change="change"
          @cancel="cancel"
        ></fui-picker>
        <fui-picker
          :options="teamOptions"
          :show="showTeam"
          @change="changeTeam"
          @cancel="cancelTeam"
        ></fui-picker>
        <fui-picker
          :options="faultOptions"
          :show="showFault"
          @change="changeFault"
          @cancel="cancelFault"
        ></fui-picker>
        <fui-picker
          :options="levelOptions"
          :show="showLevel"
          @change="changeLevel"
          @cancel="cancelLevel"
        ></fui-picker>
        <fui-picker
          :options="typeOptions"
          :show="showType"
          @change="changeType"
          @cancel="cancelType"
        ></fui-picker>
        <fui-picker
          :options="deviceOptions"
          :show="showDevice"
          @change="changeDevice"
          @cancel="cancelDevice"
        ></fui-picker>
        <fui-picker
          :options="departmentOptions"
          :show="showDepartment"
          @change="changeDepartment"
          @cancel="cancelDepartment"
        ></fui-picker>
        <fui-picker
          :options="statusOptions"
          :show="showStatus"
          @change="changeStatus"
          @cancel="cancelStatus"
        ></fui-picker>

        <!-- 日期选择器 -->
        <fui-date-picker
          range
          :show="showRepairTime"
          type="3"
          @change="changeRepairTime"
          @cancel="cancelRepairTime"
        ></fui-date-picker>

        <fui-date-picker
          range
          :show="showReceiveTime"
          type="3"
          @change="changeReceiveTime"
          @cancel="cancelReceiveTime"
        ></fui-date-picker>
      </view>
    </view>

    <!-- 固定底部按钮 -->
    <view class="fixed-bottom">
      <view class="footer">
        <view class="reset" @click="reset">重置</view>
        <view class="reset confirm" @click="handleConfirm">确定</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import {
  getFaultLibraryList,
  getRepairTeamList,
} from "@/pages/api/subpkg_institution/repairworkorder.js";

const formData = reactive({
  subject: "", // 工单主题
  orderNo: "", // 工单单号
  repairNo: "", // 报修单号
  dispatchPerson: "", // 派工人员
  startTime: "", // 维修开始时间
  endTime: "", // 维修结束时间
  repairTimeRange: "", // 维修时间范围（用于显示）
  repairTeam: "", // 维修班组
  repairPerson: "", // 维修负责人
  faultReason: "", // 故障原因
  repairLevel: "", // 维修级别
  repairType: "", // 维修类型
  emergency: "", // 紧急程度
  deviceName: "", // 设备名称
  useDepartment: "", // 使用部门
  receiver: "", // 验收人
  receiveStartTime: "", // 验收时间区间
  receiveEndTime: "", // 验收结束时间
  status: "", // 状态
  faultDescription: "", // 故障描述
  equipmentType: "", // 设备类型
  equipmentPart: "", // 设备部件
  faultCategory: "", // 故障类别
  faultEntryCode: "", // 故障编码
  faultEntryName: "", // 故障条目名称
  teamCode: "", // 团队编码
  teamLeader: "", // 团队负责人
  teamContact: "", // 团队联系人
  teamId: "", // 团队ID
  deviceId: "", // 设备ID
  deviceCode: "", // 设备编码
  location: "", // 设备位置
  assetNumber: "", // 资产编号
  deviceType: "", // 设备类型
  manufacturer: "", // 制造商
  managerName: "", // 设备管理员
  departmentId: "", // 部门ID
});

const leftClick = () => {
  uni.navigateBack();
};

// 各种选择器的显示状态
const show = ref(false);
const showTeam = ref(false);
const showFault = ref(false);
const showLevel = ref(false);
const showType = ref(false);
const showDevice = ref(false);
const showDepartment = ref(false);
const showStatus = ref(false);
const showRepairTime = ref(false);
const showReceiveTime = ref(false);

// 选项数据
const options = ref(["全部", "紧急", "高", "中", "低"]);
const teamOptions = ref([]);
const faultOptions = ref([]);
const levelOptions = ref(["全部", "大修", "中修", "小修"]);
const typeOptions = ref(["全部", "计划维修", "临时维修", "应急维修"]);
const deviceOptions = ref(["全部", "设备1", "设备2", "设备3"]);
const departmentOptions = ref(["全部", "生产部", "技术部", "质量部"]);
const statusOptions = ref(["全部", "待处理", "处理中", "已完成"]);

const mode = ref("single");

// 故障库数据
const faultList = ref([]);

// 维修班组数据
const teamList = ref([]);

// 获取故障库数据
const getFaultList = async () => {
  try {
    const params = {
      current: 1,
      size: 999,
    };
    const res = await getFaultLibraryList(params);
    if (res.code === 200 && res.success) {
      faultList.value = res.data.records;
      // 只使用faultEntryName作为选项，并去重
      const uniqueNames = new Set();
      faultOptions.value = faultList.value
        .filter((item) => {
          if (!uniqueNames.has(item.faultEntryName)) {
            uniqueNames.add(item.faultEntryName);
            return true;
          }
          return false;
        })
        .map((item) => item.faultEntryName);
    } else {
      uni.showToast({
        title: res.msg || "获取故障库数据失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("获取故障库数据失败:", error);
    uni.showToast({
      title: "获取故障库数据失败",
      icon: "none",
    });
  }
};

// 获取维修班组数据
const getTeamList = async () => {
  try {
    const params = {
      current: 1,
      size: 999,
    };
    const res = await getRepairTeamList(params);
    if (res.code === 200 && res.success) {
      teamList.value = res.data.records;
      teamOptions.value = teamList.value.map((item) => item.teamName);
    } else {
      uni.showToast({
        title: res.msg || "获取维修班组数据失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("获取维修班组数据失败:", error);
    uni.showToast({
      title: "获取维修班组数据失败",
      icon: "none",
    });
  }
};

// 显示故障选择器前确保有数据
const handleShowFault = async () => {
  if (faultOptions.value.length === 0) {
    await getFaultList();
  }
  showFault.value = true;
};

// 显示维修班组选择器前确保有数据
const handleShowTeam = async () => {
  if (teamOptions.value.length === 0) {
    await getTeamList();
  }
  showTeam.value = true;
};

// 跳转到部门选择页面
const handleShowDepartment = () => {
  uni.navigateTo({
    url: "/subpkg_institution/repairworkorder/departmentSelect",
  });
};

// 选择器change事件处理函数
const change = (e) => {
  show.value = false;
  if (e && e.value) {
    formData.emergency = e.value;
  }
};

const changeTeam = (e) => {
  showTeam.value = false;
  if (e && e.value) {
    const selectedTeam = teamList.value.find(
      (item) => item.teamName === e.value
    );
    if (selectedTeam) {
      formData.repairTeam = selectedTeam.teamName;
      formData.teamCode = selectedTeam.teamCode;
      formData.teamLeader = selectedTeam.leaderName;
      formData.teamContact = selectedTeam.contactNumber;
      formData.teamId = selectedTeam.id;
    }
  }
};

const changeFault = (e) => {
  showFault.value = false;
  if (e && e.value) {
    const selectedFault = faultList.value.find(
      (item) => item.faultEntryName === e.value
    );
    if (selectedFault) {
      formData.faultReason = selectedFault.faultReason;
      formData.faultDescription = selectedFault.faultDescription;
      formData.equipmentType = selectedFault.equipmentType;
      formData.equipmentPart = selectedFault.equipmentPart;
      formData.faultCategory = selectedFault.faultCategory;
      formData.faultEntryCode = selectedFault.faultEntryCode;
      formData.faultEntryName = selectedFault.faultEntryName;
    }
  }
};

const changeLevel = (e) => {
  showLevel.value = false;
  if (e && e.value) {
    formData.repairLevel = e.value;
  }
};

const changeType = (e) => {
  showType.value = false;
  if (e && e.value) {
    formData.repairType = e.value;
  }
};

const changeDevice = (e) => {
  showDevice.value = false;
  if (e && e.value) {
    formData.deviceName = e.value;
  }
};

const changeDepartment = (e) => {
  showDepartment.value = false;
  if (e && e.value) {
    formData.useDepartment = e.value;
    formData.departmentId = e.value.split(" ")[0];
  }
};

const changeStatus = (e) => {
  showStatus.value = false;
  if (e && e.value) {
    formData.status = e.value;
  }
};

// 取消事件处理函数
const cancel = () => (show.value = false);
const cancelTeam = () => (showTeam.value = false);
const cancelFault = () => (showFault.value = false);
const cancelLevel = () => (showLevel.value = false);
const cancelType = () => (showType.value = false);
const cancelDevice = () => (showDevice.value = false);
const cancelDepartment = () => (showDepartment.value = false);
const cancelStatus = () => (showStatus.value = false);

// 日期选择器事件处理
const changeRepairTime = (e) => {
  showRepairTime.value = false;
  if (e && e.startDate && e.endDate) {
    // 设置开始和结束时间
    formData.startTime = e.startDate.result;
    formData.endTime = e.endDate.result;
    // 在输入框中显示时间范围
    formData.repairTimeRange = `${e.startDate.result} ~ ${e.endDate.result}`;
  }
};

const changeReceiveTime = (e) => {
  showReceiveTime.value = false;
  if (e && e.startDate && e.endDate) {
    // 设置开始和结束时间
    formData.receiveStartTime = e.startDate.result;
    formData.receiveEndTime = e.endDate.result;
    // 在输入框中显示时间范围
    formData.receiveStartTime = `${e.startDate.result} ~ ${e.endDate.result}`;
  }
};

const cancelRepairTime = () => {
  showRepairTime.value = false;
};

const cancelReceiveTime = () => {
  showReceiveTime.value = false;
};

// 重置
const reset = () => {
  Object.keys(formData).forEach((key) => {
    formData[key] = "";
  });
};

const handleDeviceSelect = () => {
  // 收集所有筛选条件
  const filterParams = {
    subject: formData.subject,
    orderNo: formData.orderNo,
    repairNo: formData.repairNo,
    dispatchPerson: formData.dispatchPerson,
    startTime: formData.startTime,
    endTime: formData.endTime,
    repairTeam: formData.repairTeam,
    repairPerson: formData.repairPerson,
    faultReason: formData.faultReason,
    repairLevel: formData.repairLevel,
    repairType: formData.repairType,
    emergency: formData.emergency,
    useDepartment: formData.useDepartment,
    receiver: formData.receiver,
    receiveStartTime: formData.receiveStartTime,
    receiveEndTime: formData.receiveEndTime,
    status: formData.status,
  };

  // 将筛选条件转换为查询字符串
  const queryString = encodeURIComponent(JSON.stringify(filterParams));

  uni.navigateTo({
    url: `/subpkg_institution/repairworkorder/deviceSelect?filters=${queryString}`,
  });
};

// 在组件挂载时获取数据
onMounted(() => {
  getFaultList();
  getTeamList();

  // 添加设备选择事件监听
  uni.$on("deviceSelected", (deviceInfo) => {
    formData.deviceId = deviceInfo.deviceId;
    formData.deviceName = deviceInfo.deviceName;
  });

  // 添加部门选择事件监听
  uni.$on("departmentSelected", (departmentInfo) => {
    formData.useDepartment = departmentInfo.departmentName;
    formData.departmentId = departmentInfo.departmentId;
  });
});

// 在组件卸载时移除事件监听
onUnmounted(() => {
  uni.$off("deviceSelected");
  uni.$off("departmentSelected");
});

// 在script setup部分添加handleConfirm函数
const handleConfirm = () => {
  // 收集所有筛选条件，使用正确的参数名称
  const filterParams = {
    repairCode: formData.orderNo, // 工单单号
    repairSubject: formData.subject, // 工单主题
    applyCode: formData.repairNo, // 关联报修申请编号
    repairStaff: formData.dispatchPerson, // 派工人员
    repairStartTime: formData.startTime, // 维修开始时间起
    repairEndTime: formData.endTime, // 维修开始时间止
    repairTeam: formData.repairTeam, // 维修组
    repairManager: formData.repairPerson, // 维修负责人
    faultReason: formData.faultReason, // 故障原因
    repairType: formData.repairType, // 维修类别
    emergencyLevel: formData.emergency, // 紧急程度
    deviceName: formData.deviceName, // 设备名称
    useDept: formData.useDepartment, // 使用部门
    acceptancePersonnel: formData.receiver, // 验收人
    acceptanceStartTime: formData.receiveStartTime, // 验收时间起
    acceptanceEndTime: formData.receiveEndTime, // 验收时间止
    status: formData.status, // 状态
  };

  // 移除所有空值、undefined和null
  Object.keys(filterParams).forEach((key) => {
    if (
      filterParams[key] === "" ||
      filterParams[key] === undefined ||
      filterParams[key] === null
    ) {
      delete filterParams[key];
    }
  });

  // 发送事件并传递筛选条件
  uni.$emit("filterConditions", filterParams);

  // 返回上一页
  uni.navigateBack({
    delta: 1,
    success: () => {
      uni.showToast({
        title: "筛选条件已应用",
        icon: "success",
        duration: 2000,
      });
    },
  });
};
</script>

<style lang="scss" scoped>
page {
  height: 100vh;
}

.viewport {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
}

.fixed-top {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 99;
}

.main-content {
  flex: 1;
  overflow-y: auto;
  padding-top: 88rpx; /* 导航栏高度 */
  padding-bottom: 100rpx; /* 底部按钮高度 */
}

.warp {
  padding: 20rpx;
  .ul {
    background-color: #fff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
  }
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  z-index: 99;
}

.footer {
  display: flex;
  height: 100rpx;
  .reset {
    width: 50%;
    display: flex;
    height: 100%;
    align-items: center;
    justify-content: center;
    color: #0052d9;
    font-size: 32rpx;
    background: #fff;

    &.confirm {
      color: #fff;
      background-color: #0052d9;
    }
  }
}

.time-range {
  display: flex;
  align-items: center;
  margin-bottom: 2rpx;
  background-color: #fff;
}
</style>
